package com.atguigu.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.beans.User;
import com.atguigu.dao.UserDao;
import com.atguigu.dao.impl.UserDaoImpl;
import com.google.gson.Gson;

/**
 * 通过发送Ajax请求获取数据库中所有的员工
 */
public class GetUsersWithAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 创建UserDao对象
		UserDao userDao = new UserDaoImpl();
		// 调用UserDao中获取所有员工的方法
		List<User> users = userDao.getUsers();
		//创建Gson对象
		Gson gson = new Gson();
		//将List转换为JSON字符串
		String json = gson.toJson(users);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(json);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
